package com.ruoyi.sms.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.sms.entity.Shop;
import com.ruoyi.sms.entity.ShopVO;
import com.ruoyi.sms.mapper.ShopMapper;
import com.ruoyi.sms.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;
import java.util.logging.Logger;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kenny
 * @since 2021-11-04
 */
@Slf4j
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Autowired
    private ShopMapper mapper;
    @Autowired
    private WxMaService miniApp;

    public List<ShopVO> selectShop(ShopVO vo) {
        return mapper.selectShop(vo);
    }

    public ShopVO selectShopById(Long id) {
        return mapper.selectShopById(id);
    }

    public int insertShop(Shop smsShop) {
        int i = this.mapper.insert(smsShop);
        String img = this.createMpImg("shopId=" + smsShop.getId(), "pages/index/index", "/home/image/shop");
        smsShop.setShopImg(img);
        this.mapper.updateById(smsShop);
        return i;
    }

    /**
     * 创建带参小程序二维码
     */
    public String createMpImg(String scene, String page, String filePath) {
        try {
            File file = miniApp.getQrcodeService().createWxaCodeUnlimit(scene, page, filePath, 430, true, null, true);
            return file.getPath();
        } catch (WxErrorException e) {
            log.error(e.getMessage());
            throw new ServiceException("创建商家小程序二维码失败，请联系管理");
        }
    }
}
